/*
 * uart.c
 *
 *  Created on: Nov 13, 2013
 *      Author: PabloFR
 */

#include "uart.h"

uint8_t*  UART0_TxPtr;
uint16_t  UART0_TxSize;


void UART_ConfigBaudRate(uint32_t Baudrate){
	
	UART_BDH = UART_BDH_RXEDGIE_MASK |  (UART_SBR(Baudrate) & (0xF00))<<UART_BDH_SBR_SHIFT; 
	UART_BDL = UART_SBR(Baudrate) & (0xFF); 
	UART_C4 = UART0_C4_OSR(UART_OSR);
}

void UART_Config(void){
	
	/* Clock Gating */
	SIM_SCGC4 |= SIM_SCGC4_UART0_MASK;	//Activating Clock Gating on UART0
	SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK;	//Activating Clock Gating on PORTA
	
	/* NVIC Configuration */
	NVIC_ICPR |= (1<<12); //Clear any pending interrupts on UART0
	NVIC_ISER |= (1<<12); //Enable interrupts from UART0 Module 
		

	SIM_SOPT2 |= 1<<SIM_SOPT2_PLLFLLSEL_SHIFT | SIM_SOPT2_UART0SRC(1);		//Select PLL clock as UART Clock
	PORTA_PCR1 |= PORT_PCR_MUX(2);
	PORTA_PCR2 |= PORT_PCR_MUX(2);

	/* UART Configuration registers */
	UART_S1 = 0xFF;		//clean status flags 
	UART_C1 = UART_8BITS ;
	UART_C2 = UART_TIE_DISABLE | UART_TCIE_DISABLE | UART_RIE_ENABLE | UART_ILIE_DISABLE | UART_TX_ENABLE<<UART_C2_TE_SHIFT | UART_RX_ENABLE<<UART_C2_RE_SHIFT;	
	UART_C3 = UART_DATA_NOINV  | UART_HW_NOINT | UART_NOISE_NOINT | UART_FRAME_NOINT | UART_PARITY_NOINT;

}


uint8_t UART_TRANSMIT_Message(uint8_t *Msg, uint16_t size){
	uint8_t error;
	if((UART_S1 && (UART_S1_IDLE_MASK))!= 0 )	//if UART on Idle line (not busy)
	{
		UART0_TxPtr = Msg;	//UART pointer = message pointer
		UART0_TxSize = size ;
		UART_C2 |= UART_TCIE_ENABLE;
		error = UART_OK;
	}
	else
	{
		error = UART_ERROR_NOT_IDLE;
	}
	
	return error;
	
}


void UART0_ISR(void){

	if(UART0_TxSize>0){
		UART_D = *UART0_TxPtr;
		UART0_TxPtr++;
		UART0_TxSize--;
	}
	else
		UART_C2 = UART_TCIE_DISABLE;
	
	
	
	
}
